<template>
	<view class="view-contain" ref="rootContainer">
		<!-- 公共组件-每个页面必须引入 -->
		<public-module :leftIcon="isRequired ? '' : 'arrow-left'" :title="title" />
		<view class="form-contain">
			<u-form labelPosition="left" :model="formInfo" labelWidth="auto" ref="addForm">
				<u-form-item label="头像" prop="avatar" borderBottom>
					<button slot="right" class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseavatar">
						<u-image :src="formInfo.avatar" width="120rpx" height="120rpx" />
					</button>
				</u-form-item>
				<u-form-item label="昵称" prop="nickName" borderBottom>
					<u-input type="nickname" inputAlign="right" v-model="formInfo.nickName" border="none"
						@blur="onBlur" />
				</u-form-item>
				<u-form-item label="专业" prop="major" borderBottom>
					<view slot="right" class="picker-item" @click.stop="showMajorPicker">
						<text class="picker-text">{{ majorDisplayText || '请选择专业（最多4个）' }}</text>
						<u-icon name="arrow-right" size="16" color="#c0c4cc"></u-icon>
					</view>
				</u-form-item>
				<u-form-item label="备考城市" prop="preparationCity" borderBottom>
					<view slot="right" class="picker-item" @click.stop="showCityPicker">
						<text class="picker-text">{{ formInfo.preparationCity || '请选择备考城市' }}</text>
						<u-icon name="arrow-right" size="16" color="#c0c4cc"></u-icon>
					</view>
				</u-form-item>
				<u-form-item label="是否全职" prop="fullTime" borderBottom>
					<view slot="right" class="picker-item" @click.stop="showFullTimePicker">
						<text class="picker-text">{{ fullTimeText || '请选择工作状态' }}</text>
						<u-icon name="arrow-right" size="16" color="#c0c4cc"></u-icon>
					</view>
				</u-form-item>
				<u-form-item label="手机号" prop="phonenumber" borderBottom>
					<u-input inputAlign="right" v-model="formInfo.phonenumber" border="none" />
				</u-form-item>

			</u-form>
		</view>
		
		<!-- 专业多选弹窗 -->
		<u-popup v-if="majorPickerShow" :show="majorPickerShow" mode="bottom" @close="closeMajorPicker" :round="10">
			<view class="major-picker-popup">
				<view class="popup-header">
					<text class="header-title">选择专业</text>
					<text class="selected-count">{{ selectedMajors.length }}/4</text>
					<u-icon name="close" size="20" @click="closeMajorPicker" class="close-icon"></u-icon>
				</view>
				<scroll-view class="major-list" scroll-y>
					<view 
						v-for="(major, index) in majorList" 
						:key="index" 
						class="major-item"
						:class="{ selected: selectedMajors.includes(major) }"
						@click="toggleMajorSelection(major)"
					>
						<text class="major-text">{{ major }}</text>
						<u-icon 
							v-if="selectedMajors.includes(major)" 
							name="checkmark-circle-fill" 
							color="#2979ff" 
							size="20"
						></u-icon>
					</view>
				</scroll-view>
				<view class="popup-footer">
					<u-button @click="resetMajorSelection" type="default" size="small">重置</u-button>
					<u-button @click="confirmMajorSelection" type="primary" size="small">确定</u-button>
				</view>
			</view>
		</u-popup>
		
		<!-- 备考城市选择器 -->
		<u-picker 
			v-if="cityPickerShow" 
			ref="cityPicker" 
			:show="cityPickerShow" 
			:columns="cityColumns" 
			@close="closeCityPicker" 
			@confirm="onCityConfirm" 
			:loading="pickerLoading"
		></u-picker>
		
		<!-- 工作状态选择器 -->
		<u-picker 
			v-if="fullTimePickerShow" 
			ref="fullTimePicker" 
			:show="fullTimePickerShow" 
			:columns="fullTimeColumns" 
			@close="closeFullTimePicker" 
			@confirm="onFullTimeConfirm" 
			:loading="pickerLoading"
		></u-picker>
		
		<!-- 备考城市选择器底部按钮 -->
		<view v-if="cityPickerShow" class="picker-bottom-buttons">
			<u-button @click="confirmCitySelection" type="primary" shape="circle">确定</u-button>
		</view>
		
		<!-- 工作状态选择器底部按钮 -->
		<view v-if="fullTimePickerShow" class="picker-bottom-buttons">
			<u-button @click="confirmFullTimeSelection" type="primary" shape="circle">确定</u-button>
		</view>
		
		<view class="quit" @click="toUpdate" v-show="!majorPickerShow && !cityPickerShow && !fullTimePickerShow">
			<u-button type="primary" shape="circle">保存个人信息</u-button>
		</view>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex';
	import {
		getInfo,
		saveUserInfo
	} from "@/config/api.js"
	// 引入 u-popup 组件
	import uPopup from '@/uni_modules/uview-ui/components/u-popup/u-popup.vue';
	// 引入其他需要的组件
	import uPicker from '@/uni_modules/uview-ui/components/u-picker/u-picker.vue';
	import uForm from '@/uni_modules/uview-ui/components/u-form/u-form.vue';
	import uFormItem from '@/uni_modules/uview-ui/components/u-form-item/u-form-item.vue';
	import uInput from '@/uni_modules/uview-ui/components/u-input/u-input.vue';
	import uImage from '@/uni_modules/uview-ui/components/u-image/u-image.vue';
	import uIcon from '@/uni_modules/uview-ui/components/u-icon/u-icon.vue';
	import uButton from '@/uni_modules/uview-ui/components/u-button/u-button.vue';

	export default {
		components: {
			uPopup,
			uPicker,
			uForm,
			uFormItem,
			uInput,
			uImage,
			uIcon,
			uButton
		},
		data() {
			return {
				title: '个人资料',
				nickName: null,
				isRequired: false, // 是否为强制模式
				formInfo: {
					avatar: null,
					nickName: null,
					phonenumber: null,
					major: [], // 改为数组支持多选
					preparationCity: null,
					fullTime: null
				},
				// 专业多选相关
				selectedMajors: [], // 当前选中的专业
				// 选择器状态
				majorPickerShow: false,
				cityPickerShow: false,
				fullTimePickerShow: false,
				pickerLoading: false,
				// 专业列表
				majorList: [
					'中文文秘类', '艺术类', '法律类', '社会政治类', '经济类', '公共管理类', '工商管理类',
					'商务贸易类', '财务财会类', '税务税收类', '统计类', '审计类', '教育类',
					'外国语言文学类', '公安类', '监所管理类', '计算机类', '计算机（软件）类',
					'计算机（网络管理）类', '电子信息类', '机电控制类', '机械工程类',
					'交通工程类', '航道港口类', '船舶工程类', '水利工程类', '城建规划类',
					'土地管理类', '测绘类', '建筑工程类', '材料工程类', '地质矿产类',
					'安全生产类', '能源动力类', '环境保护类', '化学工程类', '医药化工类',
					'食品工程类', '生物工程类', '轻工纺织类', '农业类', '林业类',
					'畜牧养殖类', '医学类', '公共卫生类', '药学类', '基础理学类',
					'兵工宇航类', '仪表仪器及测试技术类', '军事学类'
				],
				// 江苏十三个地级市
				jiangsuCities: [
					'南京市', '苏州市', '无锡市', '常州市', '镇江市', '南通市', '泰州市',
					'扬州市', '盐城市', '连云港市', '徐州市', '淮安市', '宿迁市'
				],
				// 其他省份
				otherProvinces: [
					'北京市', '天津市', '上海市', '重庆市', '河北省', '山西省', '辽宁省',
					'吉林省', '黑龙江省', '安徽省', '福建省', '江西省', '山东省',
					'河南省', '湖北省', '湖南省', '广东省', '海南省', '四川省',
					'贵州省', '云南省', '陕西省', '甘肃省', '青海省', '内蒙古自治区',
					'广西壮族自治区', '西藏自治区', '宁夏回族自治区', '新疆维吾尔自治区',
					'香港特别行政区', '澳门特别行政区', '台湾省'
				],
				// 工作状态
				fullTimeOptions: ['全职', '在职', '应届生']
			}
		},
		computed: {
			...mapState(['user']),
			// 专业显示文本
			majorDisplayText() {
				if (this.formInfo.major && this.formInfo.major.length > 0) {
					if (this.formInfo.major.length <= 2) {
						return this.formInfo.major.join('、');
					} else {
						return `${this.formInfo.major.slice(0, 2).join('、')}等${this.formInfo.major.length}个`;
					}
				}
				return '';
			},
			// 城市选择器列
			cityColumns() {
				// 简化为单列选择，将江苏城市和其他省份合并
				const jiangsuWithPrefix = this.jiangsuCities.map(city => `江苏-${city}`);
				const otherWithPrefix = this.otherProvinces.map(province => `其他-${province}`);
				const allCities = [...jiangsuWithPrefix, ...otherWithPrefix];
				return [allCities];
			},
			// 工作状态选择器列
			fullTimeColumns() {
				return [this.fullTimeOptions];
			},
			// 工作状态显示文本
			fullTimeText() {
				return this.formInfo.fullTime || '';
			}
		},
		onLoad(option) {
			// 检查是否为强制模式
			if (option && option.required === 'true') {
				this.isRequired = true;
				this.title = '完善个人信息（必填）';
			}
			
			if (this.user) {
				// 工作状态反向映射：英文转中文
				const fullTimeReverseMapping = {
					'workingProfessional': '在职',
					'fullTimeStudent': '全职',
					'graduateStudent': '应届'
				};
						
				const fullTimeDisplayValue = fullTimeReverseMapping[this.user.fullTime] || this.user.fullTime;
						
				this.formInfo = {
					avatar: this.user.avatar,
					nickName: this.user.nickName,
					phonenumber: this.user.phonenumber,
					// 处理专业数据：从字符串转换为数组，如果为空则初始化为空数组
					major: this.user.major ? this.user.major.split(',').filter(item => item.trim()) : [],
					preparationCity: this.user.preparationCity || null,
					fullTime: fullTimeDisplayValue || null // 显示中文
				}
				// 初始化已选中的专业
				this.selectedMajors = [...this.formInfo.major];
			}
			
			// 确保所有选择器初始状态为关闭
			this.majorPickerShow = false;
			this.cityPickerShow = false;
			this.fullTimePickerShow = false;
			
			// 调用初始化方法
			this.initializePickers();
			
			// 添加延时再次确保选择器隐藏
			setTimeout(() => {
				this.majorPickerShow = false;
				this.cityPickerShow = false;
				this.fullTimePickerShow = false;
				this.$forceUpdate();
			}, 10);
		},
		onShow() {
			// 在强制模式下，通过页面配置禁用返回
			if (this.isRequired) {
				// 小程序中通过监听页面返回事件
				// 注意：这里我们主要通过隐藏返回按钮和路由拦截来实现
				console.log('强制模式：用户必须完善信息');
			}
			
			// 确保所有选择器都是关闭状态
			this.majorPickerShow = false;
			this.cityPickerShow = false;
			this.fullTimePickerShow = false;
			
			// 强制更新视图
			this.$forceUpdate();
			
			// 添加延时再次确保选择器隐藏
			setTimeout(() => {
				this.majorPickerShow = false;
				this.cityPickerShow = false;
				this.fullTimePickerShow = false;
				this.$forceUpdate();
			}, 10);
		},
		mounted() {
			console.log('页面已挂载，重置选择器状态');
			// 确保所有选择器初始状态为关闭
			this.majorPickerShow = false;
			this.cityPickerShow = false;
			this.fullTimePickerShow = false;
			
			// 强制更新视图
			this.$forceUpdate();
			
			// 添加延时再次确保选择器隐藏
			setTimeout(() => {
				this.majorPickerShow = false;
				this.cityPickerShow = false;
				this.fullTimePickerShow = false;
				this.$forceUpdate();
			}, 10);
			
		},
		methods: {
			...mapMutations(['setUser', 'emptyUserInfo']),
			// 初始化选择器状态
			initializePickers() {
				// 确保所有选择器都处于隐藏状态
				this.majorPickerShow = false;
				this.cityPickerShow = false;
				this.fullTimePickerShow = false;
				
				// 强制更新视图
				this.$forceUpdate();
			},
			// 添加专门的关闭方法
			closeMajorPicker() {
				this.majorPickerShow = false;
				this.$forceUpdate();
			},
			closeCityPicker() {
				this.cityPickerShow = false;
				this.$forceUpdate();
			},
			closeFullTimePicker() {
				this.fullTimePickerShow = false;
				this.$forceUpdate();
			},
			async toUpdate() {
				// 校验必填字段
				if (!this.formInfo.nickName) {
					uni.$u.toast('请填写昵称');
					return;
				}
				// 检查专业是否已选择（允许之前为空，现在通过选择器选择）
				if (!this.formInfo.major || this.formInfo.major.length === 0) {
					uni.$u.toast('请选择专业');
					return;
				}
				// 检查备考城市是否已选择（允许之前为空，现在通过选择器选择）
				if (!this.formInfo.preparationCity) {
					uni.$u.toast('请选择备考城市');
					return;
				}
				// 检查工作状态是否已选择（允许之前为空，现在通过选择器选择）
				if (!this.formInfo.fullTime) {
					uni.$u.toast('请选择工作状态');
					return;
				}
				
				// 将专业数组转换为字符串格式
				const majorString = Array.isArray(this.formInfo.major) ? this.formInfo.major.join(',') : this.formInfo.major;
				
				// 工作状态映射：中文转英文
				const fullTimeMapping = {
					'在职': 'workingProfessional',
					'全职': 'fullTimeStudent',
					'应届': 'graduateStudent'
				};
				
				const fullTimeValue = fullTimeMapping[this.formInfo.fullTime] || this.formInfo.fullTime;
				
				const res = await saveUserInfo({
					...this.formInfo,
					major: majorString, // 传送字符串格式的专业数据
					fullTime: fullTimeValue, // 传送英文参数
					userId: this.user.userId,
					loginName: this.user.loginName
				})
				if (res) {
					uni.$u.toast('保存成功')
					this.getUserInfo()
					setTimeout(() => {
						if (this.isRequired) {
							// 强制模式下，跳转到首页
							uni.reLaunch({
								url: '/pages/index/index'
							});
						} else {
							// 正常模式下，返回上一页
							uni.navigateBack({
								delta: 1
							});
						}
					}, 500)
				} else {
					this.emptyUserInfo();
					uni.showModal({
						title: '提示',
						content: '当前登录已无效，请重新登陆。',
						showCancel: false,
						success: function(res) {
							if (res.confirm) {
								uni.navigateBack({
									delta: 1
								});
							}
						}
					});
				}
			},
			async getUserInfo() {
				const res = await getInfo()
				if (res && res.user) {
					this.setUser(res.user)
					
					// 更新表单信息，将英文工作状态转换为中文
					const fullTimeReverseMapping = {
						'workingProfessional': '在职',
						'fullTimeStudent': '全职',
						'graduateStudent': '应届'
					};
					
					const fullTimeDisplayValue = fullTimeReverseMapping[res.user.fullTime] || res.user.fullTime;
					
					this.formInfo = {
						...this.formInfo,
						avatar: res.user.avatar,
						nickName: res.user.nickName,
						phonenumber: res.user.phonenumber,
						// 处理专业数据：从字符串转换为数组，如果为空则初始化为空数组
						major: res.user.major ? res.user.major.split(',').filter(item => item.trim()) : [],
						preparationCity: res.user.preparationCity || null,
						fullTime: fullTimeDisplayValue || null
					}
					// 更新已选中的专业
					this.selectedMajors = [...this.formInfo.major];
				}
			},
			onBlur(e) {
				this.formInfo.nickName = e
			},
			onChooseavatar(e) {
				this.formInfo.avatar = e.detail.avatarUrl
			},
			// 显示专业选择器
			showMajorPicker() {
				console.log('点击了专业选择器');
				// 确保其他选择器已关闭
				this.closeCityPicker();
				this.closeFullTimePicker();
				// 初始化已选中的专业（即使为空也要正确初始化）
				this.selectedMajors = this.formInfo.major ? [...this.formInfo.major] : [];
				// 显示选择器
				this.majorPickerShow = true;
				this.$forceUpdate();
				console.log('专业选择器显示状态:', this.majorPickerShow);
			},
			// 切换专业选择状态
			toggleMajorSelection(major) {
				const index = this.selectedMajors.indexOf(major);
				if (index > -1) {
					// 已选中，取消选择
					this.selectedMajors.splice(index, 1);
				} else {
					// 未选中，检查是否超过最大选择数
					if (this.selectedMajors.length >= 4) {
						uni.$u.toast('最多只能选择4个专业');
						return;
					}
					this.selectedMajors.push(major);
				}
			},
			// 重置专业选择
			resetMajorSelection() {
				this.selectedMajors = [];
			},
			// 确认专业选择
			confirmMajorSelection() {
				// 不再强制要求至少选择一个专业，允许用户清空选择
				this.formInfo.major = [...this.selectedMajors];
				// 关闭选择器
				this.closeMajorPicker();
				console.log('已选择专业:', this.formInfo.major);
			},
			// 显示城市选择器
			showCityPicker() {
				console.log('点击了城市选择器');
				// 确保其他选择器已关闭
				this.closeMajorPicker();
				this.closeFullTimePicker();
				// 显示选择器
				this.cityPickerShow = true;
				this.$forceUpdate();
				console.log('城市选择器显示状态:', this.cityPickerShow);
			},
			// 城市选择确认
			onCityConfirm(e) {
				console.log('城市选择结果:', e);
				const selectedValue = e.value[0];
				// 去掉前缀，只保留城市/省份名称
				if (selectedValue.includes('-')) {
					this.formInfo.preparationCity = selectedValue.split('-')[1];
				} else {
					this.formInfo.preparationCity = selectedValue;
				}
				// 关闭选择器
				this.closeCityPicker();
			},
			// 确认城市选择
			confirmCitySelection() {
				// 获取当前选择的值并设置到表单中
				// 通过ref获取选择器的当前值
				if (this.$refs.cityPicker) {
					const values = this.$refs.cityPicker.getValues();
					if (values && values.length > 0) {
						const selectedValue = values[0];
						// 去掉前缀，只保留城市/省份名称
						if (selectedValue.includes('-')) {
							this.formInfo.preparationCity = selectedValue.split('-')[1];
						} else {
							this.formInfo.preparationCity = selectedValue;
						}
					}
				}
				// 关闭选择器
				this.closeCityPicker();
				uni.$u.toast('城市选择已确定');
			},
			// 显示工作状态选择器
			showFullTimePicker() {
				console.log('点击了工作状态选择器');
				// 确保其他选择器已关闭
				this.closeMajorPicker();
				this.closeCityPicker();
				// 显示选择器
				this.fullTimePickerShow = true;
				this.$forceUpdate();
				console.log('工作状态选择器显示状态:', this.fullTimePickerShow);
			},
			// 工作状态选择确认
			onFullTimeConfirm(e) {
				console.log('工作状态选择结果:', e);
				// 直接存储用户选择的文本
				this.formInfo.fullTime = e.value[0];
				// 关闭选择器
				this.closeFullTimePicker();
			},
			// 确认工作状态选择
			confirmFullTimeSelection() {
				// 获取当前选择的值并设置到表单中
				// 通过ref获取选择器的当前值
				if (this.$refs.fullTimePicker) {
					const values = this.$refs.fullTimePicker.getValues();
					if (values && values.length > 0) {
						this.formInfo.fullTime = values[0];
					}
				}
				// 关闭选择器
				this.closeFullTimePicker();
				uni.$u.toast('工作状态选择已确定');
			}
		}
	}
</script>

<style lang="scss" scoped>
	.view-contain {
		position: relative;
		height: 100vh;
		overflow-y: auto;

		.avatar-wrapper {
			background-color: transparent;
			/* 透明背景 */
			border: none;
			/* 去掉边框 */
			color: inherit;
			/* 继承父元素的字体颜色 */
			padding: 0;
			/* 去掉内边距 */
		}

		:deep(.u-checkbox-group ) {
			flex-wrap: wrap;
		}

		.form-contain {
			background-color: #fff;
			border-radius: 32rpx;
			margin: 12rpx 24rpx;
			padding: 24rpx;

			.title {
				font-weight: bold;
				margin-bottom: 16rpx;
			}

			&.bottom-contain {
				margin-bottom: 200rpx;
			}
		}

		.bottom-btn-contain {
			position: fixed;
			left: 0;
			bottom: 0;
			z-index: 99;
			width: calc(100vw - 48rpx);
			height: 150rpx;
			background-color: #fff;
			padding: 48rpx 24rpx 0;
		}

		.quit {
			padding: 0 24rpx;
			margin-top: 380rpx;
		}
		
		// 选择器样式
		.picker-item {
			display: flex;
			align-items: center;
			justify-content: flex-end;
			min-height: 60rpx;
			cursor: pointer;
			
			.picker-text {
				margin-right: 10rpx;
				color: #303133;
				font-size: 28rpx;
				
				&:empty::before {
					content: attr(placeholder);
					color: #c0c4cc;
				}
			}
		}
		
		// 选择器工具栏样式
		.picker-toolbar {
			display: flex;
			justify-content: space-between;
			align-items: center;
			height: 44px;
			padding: 0 16px;
			background-color: #fff;
			border-bottom: 1rpx solid #eee;
		}
		
		.toolbar-btn {
			font-size: 16px;
			color: #2979ff;
			padding: 8px 12px;
		}
		
		.toolbar-title {
			font-size: 16px;
			font-weight: bold;
			color: #333;
		}
		
		// 选择器底部按钮样式
		.picker-bottom-buttons {
			position: fixed;
			bottom: 20rpx;
			left: 24rpx;
			right: 24rpx;
			z-index: 1000;
			padding: 20rpx;
			background-color: #fff;
			border-top: 1rpx solid #eee;
		}
		
		// 专业多选弹窗样式
		.major-picker-popup {
			padding: 20rpx;
			height: 60vh;
			display: flex;
			flex-direction: column;
			
			.popup-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 20rpx 0;
				border-bottom: 1rpx solid #eee;
				
				.header-title {
					font-size: 32rpx;
					font-weight: bold;
				}
				
				.selected-count {
					font-size: 28rpx;
					color: #2979ff;
				}
				
				.close-icon {
					padding: 10rpx;
				}
			}
			
			.major-list {
				flex: 1;
				margin: 20rpx 0;
				
				.major-item {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding: 24rpx 0;
					border-bottom: 1rpx solid #f5f5f5;
					
					&.selected {
						.major-text {
							color: #2979ff;
							font-weight: bold;
						}
					}
					
					.major-text {
						font-size: 28rpx;
						color: #333;
					}
				}
			}
			
			.popup-footer {
				display: flex;
				justify-content: space-between;
				gap: 20rpx;
				
				.u-button {
					flex: 1;
				}
			}
		}
	}
</style>